package com.ssm.controller;

import com.ssm.utils.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
public class UploadController {

    @RequestMapping("/pic")
    public String upload(MultipartFile file) throws Exception {
        String fileName = file.getOriginalFilename();
        String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
        //存储路径
        //String filePath = config.getLocalPath();
        String filePath = "C:/upload";
        String os = System.getProperty("os.name");
        if(os.toLowerCase().startsWith("win")){
            filePath = "C:/upload";
            //System.out.println(os + " can't gunzip");
        }else {
            filePath = "/usr/upload";
        }
        //文件名称
        String storedFileName = getPath("") + "." + prefix;
        File fileLo = new File(filePath + "/"+storedFileName);
        if(fileLo.exists() == false){
            fileLo.mkdirs();
        }
        file.transferTo(fileLo);
        //域名+前缀+文件名
        return  "upload/"+storedFileName;
    }

    public String getPath(String prefix) {
        //生成uuid
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        //文件路径
        String path = DateUtils.format(new Date(), "yyyyMMdd") + "/" + DateUtils.format(new Date(), "HHmmssS") + uuid.substring(0, 5);

        if (StringUtils.isNotBlank(prefix)) {
            path = prefix + "/" + path;
        }

        return path;
    }


}
